package com.lulu.baselib.util;

import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;

import com.lulu.baselib.MyApplication;

/**
 * Author: XuChang
 * Date: 2019/10/20 21:52
 * Email: 123286473@qq.com
 * Description:
 * History:
 */
public class ToastUtil {
    static Toast lastToast;

//    private static Toast getToast(Context context, String msg) {
//        if (toast == null) {
//            synchronized (ToastUtil.class) {
//                if (toast == null)
//                    toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
//            }
//        } else {
//            toast.setText(msg);
//        }
//        toast.setGravity(Gravity.CENTER, 0, 0);
//        return toast;
//    }

    private static Toast getToast(String msg){
        if(lastToast!=null){
            lastToast.cancel();
        }
        Toast toast = Toast.makeText(MyApplication.getInstance(), msg, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        return toast;
    }

    public static void toast(String msg) {
        if (isMainThread())
            toastAction(msg);
        else
            new Handler(Looper.getMainLooper()).post(() -> toastAction(msg));
    }

    private static void toastAction(String msg) {
        getToast(msg).show();
    }

    private static boolean isMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }
}
